{% extends "pc/template.html" %}

{% block title %}
报废列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
    .swal2-container { z-index: 99999 !important; }
    .swal2-popup { z-index: 99999 !important; }
    .swal2-backdrop-show { z-index: 99998 !important; }
    .modal { z-index: 1050; }
    .modal-backdrop { z-index: 1040; }
    .card { margin: 1.5rem 0; border: none; box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075); border-radius: 0.5rem; transition: all 0.3s; }
    .card-header { background: #fff; border-bottom: 1px solid rgba(0,0,0,0.05); padding: 1.25rem 1.5rem; border-radius: 0.5rem 0.5rem 0 0; }
    .card-header h5 { color: #566a7f; font-weight: 600; margin: 0; }
    .table-responsive { margin: 0; padding: 0 1.5rem; }
    .table { margin: 1rem 0; border-collapse: separate; border-spacing: 0; }
    .table th { background: #f8f9fa; color: #566a7f; font-weight: 600; padding: 1rem; border-bottom: 2px solid #e9ecef; white-space: nowrap; }
    .table td { padding: 1rem; vertical-align: middle; border-bottom: 1px solid #e9ecef; color: #697a8d; transition: all 0.2s; }
    .table tbody tr { transition: all 0.2s; }
    .table tbody tr:hover { background-color: #f8f9fa; transform: translateY(-1px); }
    .action-buttons .btn {
        padding: 0.4rem 0.6rem;
        margin: 0 0.2rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }
    .action-buttons .btn:hover {
        transform: translateY(-2px);
    }
    .btn-info { background-color: #71ddff; border-color: #71ddff; color: #fff; }
    .btn-info:hover { background-color: #4fd4ff; border-color: #4fd4ff; }
    .btn-danger { background-color: #ff8590; border-color: #ff8590; }
    .btn-danger:hover { background-color: #ff6b78; border-color: #ff6b78; }
    .status-badge { padding: 0.5em 0.75em; font-size: 0.75em; font-weight: 600; border-radius: 0.375rem; display: inline-block; text-align: center; min-width: 80px; }
    .status-shelf { background-color: #e6f7ff; color: #1890ff; border: 1px solid #1890ff; }
    .status-warehouse { background-color: #f6ffed; color: #52c41a; border: 1px solid #52c41a; }
    .scrap-image { width: 60px; height: 60px; object-fit: cover; border-radius: 0.5rem; box-shadow: 0 2px 4px rgba(0,0,0,0.1); transition: all 0.3s; }
    .scrap-image:hover { transform: scale(1.1); box-shadow: 0 4px 8px rgba(0,0,0,0.15); }
    .remark-ellipsis { max-width: 120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: help; }
    .action-btn {
        background: #f8f9fa;
        border: 1px solid #d9dee3;
        color: #697a8d;
        padding: 0.4rem 0.8rem;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
        font-size: 1rem;
        font-weight: 500;
    }
    .action-btn:hover {
        background: #f5f5f9;
        border-color: #d9dee3;
        color: #566a7f;
    }
    .action-btn i {
        font-size: 1.1rem;
    }
    .dropdown-menu {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        padding: 0.5rem;
        min-width: 160px;
    }
    .dropdown-item {
        padding: 0.6rem 1rem;
        color: #697a8d;
        border-radius: 0.4rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
        font-size: 1rem;
    }
    .dropdown-item.edit { color: #ffab00; }
    .dropdown-item.delete { color: #ff3e1d; }
    .dropdown-item.edit:hover { background: rgba(255, 171, 0, 0.1); }
    .dropdown-item.delete:hover { background: rgba(255, 62, 29, 0.1); }
    .dropdown-toggle::after { display: none; }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">报废列表</h5>
            <div>
                <button type="button" class="btn btn-primary" onclick="showAddScrapModal()">
                    <i class="bx bx-plus"></i> 新增报废
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-md-4">
                    <input type="text" class="form-control" id="scrapSearchInput" placeholder="搜索商品名称/ID/操作员/原因/报废ID" oninput="onScrapSearch()">
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>图片</th>
                            <th>商品名称</th>
                            <th>报废数量</th>
                            <th>报废位置</th>
                            <th>操作员</th>
                            <th>报废时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="scrapTableBody">
                        <!-- 报废数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination" id="scrapPagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>
    <!-- 预留：新增/编辑报废模态框 -->
    <div id="scrapModalContainer">
      <div class="modal fade" id="addScrapModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">新增报废</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <form id="addScrapForm">
                <div class="row">
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">商品 <span class="text-danger">*</span></label>
                      <select class="form-select" id="scrapProductSelect" name="scrap_product" required></select>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">报废数量 <span class="text-danger">*</span></label>
                      <input type="number" class="form-control" id="scrapNumberInput" name="scrap_number" min="1" required>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">报废位置 <span class="text-danger">*</span></label>
                      <div>
                        <div class="form-check form-check-inline">
                          <input class="form-check-input" type="radio" name="scrap_location" id="scrapLocationShelf" value="1" checked>
                          <label class="form-check-label" for="scrapLocationShelf">货架</label>
                        </div>
                        <div class="form-check form-check-inline">
                          <input class="form-check-input" type="radio" name="scrap_location" id="scrapLocationWarehouse" value="2">
                          <label class="form-check-label" for="scrapLocationWarehouse">仓库</label>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">操作员 <span class="text-danger">*</span></label>
                      <select class="form-select" id="scrapUserSelect" name="scrap_user" required></select>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">报废图片</label>
                      <input type="file" class="form-control" id="scrapImageInput" name="images" multiple accept="image/*">
                      <small class="text-muted">可多选，支持jpg/png等格式</small>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">报废原因</label>
                      <textarea class="form-control" id="scrapReasonInput" name="scrap_reason" rows="2" maxlength="200" placeholder="可选，最多200字"></textarea>
                    </div>
                  </div>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" onclick="addScrap()">添加</button>
            </div>
          </div>
        </div>
      </div>
      <div class="modal fade" id="editScrapModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">编辑报废</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <form id="editScrapForm">
                <input type="hidden" id="editScrapId">
                <div class="row">
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">商品</label>
                      <input class="form-control" id="editScrapProduct" name="scrap_product" readonly>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">报废数量 <span class="text-danger">*</span></label>
                      <input type="number" class="form-control" id="editScrapNumberInput" name="scrap_number" min="1" required>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">报废位置 <span class="text-danger">*</span></label>
                      <div>
                        <div class="form-check form-check-inline">
                          <input class="form-check-input" type="radio" name="scrap_location" id="editScrapLocationShelf" value="1">
                          <label class="form-check-label" for="editScrapLocationShelf">货架</label>
                        </div>
                        <div class="form-check form-check-inline">
                          <input class="form-check-input" type="radio" name="scrap_location" id="editScrapLocationWarehouse" value="2">
                          <label class="form-check-label" for="editScrapLocationWarehouse">仓库</label>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">操作员 <span class="text-danger">*</span></label>
                      <select class="form-select" id="editScrapUserSelect" name="scrap_user" required></select>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">报废图片</label>
                      <div id="editScrapImagePreview" class="mb-2"></div>
                      <input type="file" class="form-control" id="editScrapImageInput" name="images" multiple accept="image/*">
                      <small class="text-muted">可多选，支持jpg/png等格式</small>
                    </div>
                    <div class="mb-3">
                      <label class="form-label">报废原因</label>
                      <textarea class="form-control" id="editScrapReasonInput" name="scrap_reason" rows="2" maxlength="200" placeholder="可选，最多200字"></textarea>
                    </div>
                  </div>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" onclick="updateScrap()">保存</button>
            </div>
          </div>
        </div>
      </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    let allScraps = [];
    let currentScrapPage = 1;
    const scrapItemsPerPage = 10;
    let scrapSearchKeyword = '';

    document.addEventListener('DOMContentLoaded', function() {
        getScrapList();
    });

    // 获取报废列表
    function getScrapList() {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });
        axios.get('/api/scrap/get_scrap_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    allScraps = response.data.data;
                    currentScrapPage = 1;
                    renderScrapTable();
                    renderScrapPagination();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function() {
                Swal.fire('错误', '获取报废列表失败', 'error');
            })
            .finally(function() { loadingToast.close(); });
    }

    // 搜索
    function onScrapSearch() {
        scrapSearchKeyword = document.getElementById('scrapSearchInput').value.trim();
        currentScrapPage = 1;
        renderScrapTable();
        renderScrapPagination();
    }

    // 渲染表格
    function renderScrapTable() {
        const tbody = document.getElementById('scrapTableBody');
        tbody.innerHTML = '';
        let filtered = allScraps;
        if (scrapSearchKeyword) {
            const kw = scrapSearchKeyword.toLowerCase();
            filtered = allScraps.filter(item => {
                return (item.product?.name || '').toLowerCase().includes(kw)
                    || (item.user?.username || '').toLowerCase().includes(kw)
                    || (item.scrap_number + '').includes(kw)
                    || (item.scrap_location === 1 ? '货架' : '仓库').includes(kw)
                    || (item.create_time || '').toLowerCase().includes(kw);
            });
        }
        const start = (currentScrapPage - 1) * scrapItemsPerPage;
        const end = start + scrapItemsPerPage;
        const pageData = filtered.slice(start, end);
        pageData.forEach(scrap => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                  ${scrap.images && scrap.images.length > 0 ?
                    `<img src="${scrap.images[0].image}" class="scrap-image" alt="图片">` :
                    '<span class="text-muted">无图片</span>'}
                </td>
                <td>${scrap.product?.name || '-'}</td>
                <td>${scrap.scrap_number}</td>
                <td>
                  <span class="status-badge ${scrap.scrap_location === 1 ? 'status-shelf' : 'status-warehouse'}">
                    ${scrap.scrap_location === 1 ? '货架' : '仓库'}
                  </span>
                </td>
                <td>${scrap.user?.username || '-'}</td>
                <td>${scrap.create_time || '-'}</td>
                <td class="action-buttons">
                  <div class="dropdown">
                    <button class="action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                      <i class="bx bx-dots-vertical-rounded"></i>
                      <span>操作</span>
                    </button>
                    <ul class="dropdown-menu">
                      <li>
                        <a class="dropdown-item edit" href="#" onclick="editScrap('${scrap.scrap_id}')">
                          <i class="bx bx-edit"></i>
                          <span>编辑</span>
                        </a>
                      </li>
                      <li>
                        <a class="dropdown-item delete" href="#" onclick="deleteScrap('${scrap.scrap_id}')">
                          <i class="bx bx-trash"></i>
                          <span>删除</span>
                        </a>
                      </li>
                      <!-- 预留更多操作 -->
                    </ul>
                  </div>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    // 渲染分页
    function renderScrapPagination() {
        const pagination = document.getElementById('scrapPagination');
        const filtered = scrapSearchKeyword ? allScraps.filter(item => {
            const kw = scrapSearchKeyword.toLowerCase();
            return (item.product?.name || '').toLowerCase().includes(kw)
                || (item.user?.username || '').toLowerCase().includes(kw)
                || (item.scrap_number + '').includes(kw)
                || (item.scrap_location === 1 ? '货架' : '仓库').includes(kw)
                || (item.create_time || '').toLowerCase().includes(kw);
        }) : allScraps;
        const totalPages = Math.ceil(filtered.length / scrapItemsPerPage);
        let html = '';
        html += `<li class="page-item ${currentScrapPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changeScrapPage(${currentScrapPage - 1})" aria-label="Previous">
                <i class="bx bx-chevron-left"></i>
            </a>
        </li>`;
        for (let i = 1; i <= totalPages; i++) {
            html += `<li class="page-item ${currentScrapPage === i ? 'active' : ''}">
                <a class="page-link" href="#" onclick="changeScrapPage(${i})">${i}</a>
            </li>`;
        }
        html += `<li class="page-item ${currentScrapPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changeScrapPage(${currentScrapPage + 1})" aria-label="Next">
                <i class="bx bx-chevron-right"></i>
            </a>
        </li>`;
        pagination.innerHTML = html;
    }

    function changeScrapPage(page) {
        const filtered = scrapSearchKeyword ? allScraps.filter(item => {
            const kw = scrapSearchKeyword.toLowerCase();
            return (item.product?.name || '').toLowerCase().includes(kw)
                || (item.user?.username || '').toLowerCase().includes(kw)
                || (item.scrap_number + '').includes(kw)
                || (item.scrap_location === 1 ? '货架' : '仓库').includes(kw)
                || (item.create_time || '').toLowerCase().includes(kw);
        }) : allScraps;
        const totalPages = Math.ceil(filtered.length / scrapItemsPerPage);
        if (page < 1 || page > totalPages) return;
        currentScrapPage = page;
        renderScrapTable();
        renderScrapPagination();
    }

    // 编辑报废（预留）
    function editScrap(scrapId) {
        // 获取操作员下拉
        getUserOptionsEdit();
        // 获取报废详情
        axios.get(`/api/scrap/get_scrap/${scrapId}/`).then(function(res) {
            if (res.data.code === 200) {
                const scrap = res.data.data;
                document.getElementById('editScrapId').value = scrap.scrap_id;
                document.getElementById('editScrapProduct').value = scrap.product?.product_id || '';
                document.getElementById('editScrapProduct').setAttribute('data-display', 
                    `${scrap.product?.name || ''}（库存:${scrap.product?.stock ?? '-'} 货架:${scrap.product?.shelf_number ?? '-'} 仓库:${scrap.product?.warehouse_number ?? '-'})`);
                document.getElementById('editScrapNumberInput').value = scrap.scrap_number;
                document.getElementById('editScrapReasonInput').value = scrap.scrap_reason || '';
                // 位置
                if (scrap.scrap_location == 1) {
                    document.getElementById('editScrapLocationShelf').checked = true;
                } else {
                    document.getElementById('editScrapLocationWarehouse').checked = true;
                }
                // 操作员
                setTimeout(() => {
                    document.getElementById('editScrapUserSelect').value = scrap.user?.id || '';
                }, 200);
                // 图片预览
                renderEditScrapImages(scrap.images || []);
                // 清空新上传图片
                document.getElementById('editScrapImageInput').value = '';
                // 弹窗
                const modal = new bootstrap.Modal(document.getElementById('editScrapModal'));
                modal.show();
            } else {
                Swal.fire('错误', res.data.msg, 'error');
            }
        });
    }

    // 获取操作员下拉（编辑）
    function getUserOptionsEdit() {
        axios.get('/api/users/get_user_list/').then(function(res) {
            if (res.data.code === 200) {
                const select = document.getElementById('editScrapUserSelect');
                select.innerHTML = '<option value="">请选择操作员</option>' +
                    res.data.data.map(u => `<option value="${u.id}">${u.username}</option>`).join('');
            }
        });
    }

    // 编辑图片预览
    function renderEditScrapImages(images) {
        const container = document.getElementById('editScrapImagePreview');
        container.innerHTML = '';
        images.forEach(img => {
            const div = document.createElement('div');
            div.className = 'd-inline-block position-relative me-2 mb-2';
            div.innerHTML = `<img src="${img.image}" style="width:60px;height:60px;border-radius:8px;object-fit:cover;box-shadow:0 2px 4px rgba(0,0,0,0.1);"><button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0" style="padding:2px 6px;font-size:14px;line-height:1;" onclick="deleteEditScrapImage(${img.id})">×</button>`;
            container.appendChild(div);
        });
    }

    // 删除已上传图片
    function deleteEditScrapImage(imageId) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这张图片吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                axios.delete(`/api/scrap/delete_scrap_image/${imageId}/`).then(function(res) {
                    if (res.data.code === 200) {
                        Swal.fire({ icon: 'success', title: '成功', text: '图片删除成功', showConfirmButton: false, timer: 1200 });
                        // 重新加载图片
                        const scrapId = document.getElementById('editScrapId').value;
                        axios.get(`/api/scrap/get_scrap/${scrapId}/`).then(function(res2) {
                            if (res2.data.code === 200) {
                                renderEditScrapImages(res2.data.data.images || []);
                            }
                        });
                    } else {
                        Swal.fire('错误', res.data.msg, 'error');
                    }
                });
            }
        });
    }

    // 编辑报废提交
    function updateScrap() {
        const form = document.getElementById('editScrapForm');
        const formData = new FormData(form);
        const scrapId = document.getElementById('editScrapId').value;
        // 确保scrap_product字段是product_id
        formData.set('scrap_product', document.getElementById('editScrapProduct').value);
        // 校验
        if (!formData.get('scrap_product')) {
            Swal.fire('错误', '商品信息无效', 'error'); return;
        }
        if (!formData.get('scrap_number') || parseInt(formData.get('scrap_number')) <= 0) {
            Swal.fire('错误', '请输入有效的报废数量', 'error'); return;
        }
        if (!formData.get('scrap_user')) {
            Swal.fire('错误', '请选择操作员', 'error'); return;
        }
        // 立即关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('editScrapModal'));
        modal.hide();
        const loadingToast = Swal.fire({ title: '保存中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
        // 提交主表单
        axios.post(`/api/scrap/update_scrap/${scrapId}/`, formData)
            .then(function(res) {
                if (res.data.code === 200) {
                    // 上传新图片（如有）
                    const images = document.getElementById('editScrapImageInput').files;
                    if (images.length > 0) {
                        const uploadPromises = Array.from(images).map(img => {
                            const imgForm = new FormData();
                            imgForm.append('image', img);
                            return axios.post(`/api/scrap/upload_scrap_image/${scrapId}/`, imgForm);
                        });
                        Promise.all(uploadPromises).then(() => {
                            Swal.fire({ icon: 'success', title: '成功', text: '报废更新成功', showConfirmButton: false, timer: 1500 });
                            getScrapList();
                        }).catch(() => {
                            Swal.fire('警告', '报废已更新，但部分图片上传失败', 'warning');
                            getScrapList();
                        }).finally(() => loadingToast.close());
                    } else {
                        Swal.fire({ icon: 'success', title: '成功', text: '报废更新成功', showConfirmButton: false, timer: 1500 });
                        getScrapList();
                        loadingToast.close();
                    }
                } else {
                    Swal.fire('错误', res.data.msg, 'error');
                    loadingToast.close();
                }
            })
            .catch(function() {
                Swal.fire('错误', '报废更新失败', 'error');
                loadingToast.close();
            });
    }

    // 新增报废弹窗
    function showAddScrapModal() {
      getProductOptions();
      getUserOptions();
      document.getElementById('addScrapForm').reset();
      const modal = new bootstrap.Modal(document.getElementById('addScrapModal'));
      modal.show();
    }

    // 获取商品下拉
    function getProductOptions() {
      axios.get('/api/product/get_product_list/').then(function(res) {
        if (res.data.code === 200) {
          const select = document.getElementById('scrapProductSelect');
          select.innerHTML = '<option value="">请选择商品</option>' +
            res.data.data.map(p => `<option value="${p.product_id}">${p.name}（库存:${p.stock} 货架:${p.shelf_number} 仓库:${p.warehouse_number}）</option>`).join('');
        }
      });
    }
    // 获取操作员下拉
    function getUserOptions() {
      axios.get('/api/users/get_user_list/').then(function(res) {
        if (res.data.code === 200) {
          const select = document.getElementById('scrapUserSelect');
          select.innerHTML = '<option value="">请选择操作员</option>' +
            res.data.data.map(u => `<option value="${u.id}">${u.username}</option>`).join('');
        }
      });
    }

    // 新增报废提交
    function addScrap() {
      const form = document.getElementById('addScrapForm');
      const formData = new FormData(form);
      // 校验
      if (!formData.get('scrap_product')) {
        Swal.fire('错误', '请选择商品', 'error'); return;
      }
      if (!formData.get('scrap_number') || parseInt(formData.get('scrap_number')) <= 0) {
        Swal.fire('错误', '请输入有效的报废数量', 'error'); return;
      }
      if (!formData.get('scrap_user')) {
        Swal.fire('错误', '请选择操作员', 'error'); return;
      }
      // 立即关闭模态框
      const modal = bootstrap.Modal.getInstance(document.getElementById('addScrapModal'));
      modal.hide();
      const loadingToast = Swal.fire({ title: '添加中...', allowOutsideClick: false, didOpen: () => { Swal.showLoading(); } });
      // 提交主表单
      axios.post('/api/scrap/create_scrap/', formData)
        .then(function(res) {
          if (res.data.code === 200) {
            // 上传图片（如有）
            const scrapId = res.data.data.scrap_id;
            const images = document.getElementById('scrapImageInput').files;
            if (images.length > 0) {
              const uploadPromises = Array.from(images).map(img => {
                const imgForm = new FormData();
                imgForm.append('image', img);
                return axios.post(`/api/scrap/upload_scrap_image/${scrapId}/`, imgForm);
              });
              Promise.all(uploadPromises).then(() => {
                Swal.fire({ icon: 'success', title: '成功', text: '报废添加成功', showConfirmButton: false, timer: 1500 });
                getScrapList();
              }).catch(() => {
                Swal.fire('警告', '报废已添加，但部分图片上传失败', 'warning');
                getScrapList();
              }).finally(() => loadingToast.close());
            } else {
              Swal.fire({ icon: 'success', title: '成功', text: '报废添加成功', showConfirmButton: false, timer: 1500 });
              getScrapList();
              loadingToast.close();
            }
          } else {
            Swal.fire('错误', res.data.msg, 'error');
            loadingToast.close();
          }
        })
        .catch(function() {
          Swal.fire('错误', '添加报废失败', 'error');
          loadingToast.close();
        });
    }

    // 删除报废
    function deleteScrap(scrapId) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这条报废记录吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => { Swal.showLoading(); }
                });
                axios.delete(`/api/scrap/delete_scrap/${scrapId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({ icon: 'success', title: '成功', text: '报废记录删除成功', showConfirmButton: false, timer: 1500 });
                            getScrapList();
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function() {
                        Swal.fire('错误', '删除报废记录失败', 'error');
                    })
                    .finally(function() { loadingToast.close(); });
            }
        });
    }
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}